package com.jied.duodian.service.Impl;

import com.jied.duodian.dao.DdUserRoleDAO;
import com.jied.duodian.entity.DdUser;
import com.jied.duodian.entity.DdUserRole;
import com.jied.duodian.entity.DdUserRoleExample;
import com.jied.duodian.entity.Dutity.DdOUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @author LiJie
 * @date Created on 2020/10/30
 * WWW https://github.com/j6l
 */
@Service
@Slf4j
@Transactional
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    DdUserRoleDAO ddUserRoleDAO;
    @Autowired
    private DdUserServiceImpl userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DdUser user = userService.getUserByName( username );
        if (user == null) {
            throw new UsernameNotFoundException( String.format( "%s.这个用户不存在", username ) );
        }
        if (user.getStatus() == 0) {
            throw new UsernameNotFoundException( String.format( "%s.这个用户被封禁", username ) );
        }
        log.info( "登录的用户数据为{}", user );
        return new DdOUser( user.getUsername(), user.getPassword(), getUserRole( user.getRole() ) );
    }


    /**
     * 使用role查询ddUserRole数据 使用流转换成权限
     *
     * @param role Role数据
     * @return
     */
    public List<SimpleGrantedAuthority> getUserRole(Integer role) {
        DdUserRoleExample example = new DdUserRoleExample();
        DdUserRoleExample.Criteria criteria = example.createCriteria();
        criteria.andStarusEqualTo( role );
        List<DdUserRole> ddUserRoles = ddUserRoleDAO.selectByExample( example );
        return ddUserRoles.stream().map( DdUserRole::getRole )
                .map( SimpleGrantedAuthority::new ).collect( Collectors.toList() );

    }
}
